<template>
  <div class="generatePPT" v-loading="loading" element-loading-text="上传中..."
    element-loading-background="rgba(0, 0, 0, 0.8)" element-loading-spinner="el-icon-loading">
    <header class="header">
      <span @click="emit('back')"></span>
      <span v-if="prop.message">编辑笔记</span>
      <span v-else>新建笔记</span>
      <el-button style="margin-left: auto;" type="primary" @click="noteTitleInput">保存</el-button>
    </header>


    <textarea id="default" style="width: 100%;height: 100%;"></textarea>
    <!-- <VAceEditor class="editor-card"
          v-model:value="code"
          :lang="language"
          :theme="theme"
          :options="editorOptions"
          style="height: 100%; width: 100%"
      /> -->
    <div class="btn" style="display: flex;justify-content: center;align-items: center;">
      <span @click="inputImg.click()"><img
          src="http://igrsbj.oss-cn-beijing.aliyuncs.com/jar/CloudBoard_xz/icons/%E5%9B%BE%E7%89%87.svg"
          alt="点击插入图片" /></span>
      <input type="file" ref="inputImg" style="display: none;" @input="updateImg" accept="image/*" />
      <span @click="FileDialog = true"><img
          src="http://igrsbj.oss-cn-beijing.aliyuncs.com/jar/CloudBoard_xz/icons/%E5%9B%BE%E7%89%87.svg"
          alt="点击插入图片" /></span>
    </div>
    <el-dialog :show-close="false" align-center v-model="FileDialog" class="PPT-FileDialog" :before-close="handleClose">
      <FileSAearch message="确认" @download="download" class="PPT-Fileitem" :isEditor="isEditor" />
    </el-dialog>

  </div>
  <el-dialog v-model="dialogFormVisible" title="请输入笔记主题" width="500">
    <el-form :model="formInput">
      <el-form-item label="笔记主题" :label-width="formLabelWidth">
        <el-input v-model="formInput.name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadNote">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { downLoadNote, uploadImg, htmlToDocx } from "@/api/index.js";
import mammoth from 'mammoth';
import { useRouter } from "vue-router";
const router = useRouter();
const topicFileName = ref('');
import { saveAs } from 'file-saver'
import FileSAearch from '@/views/PocketAI/components/FileSAearch.vue';

const isEditor = ref(true)
const dialogFormVisible = ref(false)
const FileDialog = ref(false)
const code = ref(``);
const language = ref('javascript');
const inputImg = ref(null);
const fileName = ref('')
const theme = ref('github');
const dataList = ref([])
const loading = ref(false);
const formInput = ref({
  name:""
})
const formLabelWidth = '100px'
import { ElMessage } from 'element-plus'
const prop = defineProps({
  message: {
    type: Boolean,
  },
  path: {
    type: String,
  }
})

const download = (fileList) => {
  dataList.value = fileList
  FileDialog.value = false
}

const emit = defineEmits(['back'])
const updateImg = (e) => {
  var file = event.target.files[0]; // 获取选中的文件
  var reader = new FileReader(); // 创建FileReader对象

  // 监听FileReader的load事件
  reader.onload = function (e) {
    // 将读取的图片URL设置给img元素的src属性
    // imagePreview.src = e.target.result;
    tinymce.activeEditor.insertContent('<img src="' + e.target.result + '" alt="Uploaded Image" />');
  };

  // 读取文件内容为Data URL
  if (file) {
    reader.readAsDataURL(file);
  }
}
const noteTitleInput = () =>{
  if(fileName.value === '') {
    dialogFormVisible.value = true
  }else{
    uploadNote()
  }
}
const uploadNote = async () => {
  dialogFormVisible.value = false
  loading.value = true
  console.log(loading.value)
  var content = tinymce.activeEditor.getContent()
  const blob = new Blob([content], { type: 'text/plain' });
  // 创建 a 元素用于下载
  const formData1 = new FormData();
  formData1.append("html_file", blob)
  htmlToDocx(formData1).then((res) => {
    const formData = new FormData();
    formData.append('file', res)
    formData.append("chunkNumber", 1)
    formData.append("chunkSize", res.size)
    formData.append("currentChunkSize", 1048)
    formData.append("totalSize", 1048)
    formData.append("identifier", `1048-docx`)
    if(fileName.value === '') {
      formData.append("filename", formInput.value.name + '.docx')
      formData.append("relativePath", formInput.value.name + '.docx')
    }else{
      formData.append("filename", fileName.value)
      formData.append("relativePath", fileName.value)
    }

    formData.append("totalChunks", 1)
    formData.append("path", '/DATA/notes')
    uploadImg(formData)
    loading.value = false
    console.log(loading.value)
    ElMessage.success("上传成功")
  }).catch((error) => {
    ElMessage.success("上传失败")
  });
}


onMounted(() => {
  tinymce.init({
    selector: 'textarea#default',
    plugins: 'image',
    content_style: "img{border-radius: 8px;}",

  });
  // const imageSrc = '<img src="image.jpg" alt="描述性文本">';
  // code.value = imageSrc

  if (prop.message == true) {
    var paramList = []
    paramList.push(prop.path)
    downLoadNote(paramList).then(response => {
      console.log(getFileNameFromPath(prop.path))
      fileName.value = getFileNameFromPath(prop.path)
      const blob = new Blob([response], { type: 'application/docx' });
      const reader = new FileReader();
      reader.readAsArrayBuffer(blob); // 读取文件为 ArrayBuffer
      reader.onload = async (loadEvent) => {
        const arrayBuffer = loadEvent.target.result;
        console.log(arrayBuffer)
        mammoth.convertToHtml({ arrayBuffer: arrayBuffer }).then(res => {
          console.log(res)
          tinymce.activeEditor.setContent(res.value)

        });
      }
    })
  }
})

onUnmounted(() => {
  tinymce.get().forEach(function (editor) {
    editor.remove();
  });
  formInput.value.name = ''
  prop.message = false
})
const getFileNameFromPath = (filePath) => {
  return filePath.split('/').pop().split('\\').pop();
}

</script>

<style lang="scss" scoped>
.generatePPT {
  flex-direction: column;
  align-item: start;
  width: 100%;
  height: 100%;
  padding: 30px 66px;

  .header {
    width: 100%;
    height: 30px;
    display: flex;
    align-items: center;

    span {
      font-weight: 600;
      margin-right: 8px;

      &:nth-child(1) {
        text-align: end;
        width: 58px;
        height: 20px;
        cursor: pointer;
        background: url('@/assets/image/左箭头.svg') no-repeat left;
      }
    }

    .el-button {
      width: 80px;
      height: 32px;
      border-radius: 6px;
    }
  }


  .editor-card {
    height: 100%;
    margin-top: 30px;

    .content {
      width: 100%;
      border-radius: 6px;
      background: #F6F6F6;
      padding-top: 8px;
      padding-bottom: 8px;
      margin-top: 8px;


    }

    .btn {
      display: flex;

      justify-content: center;
      align-items: center;

      span {
        background-color: #EFF0F4;
        width: 60px;
        height: 44px;

        &:nth-child(1) {
          background: url('@/icons/新建.svg') no-repeat left;
        }
      }
    }
  }


}

:deep(.tox-tinymce) {
  width: 100%;
  height: 100%;

  .tox-statusbar,
  .tox-editor-header {

    display: none !important;
  }

}
</style>
